package com.jxmcloud.business.cut.service.impl.nah.login;

import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxmcloud.business.ce.model.CeSysParameter;
import com.jxmcloud.business.ce.service.ICeSysParameterService;
import com.jxmcloud.business.cut.constants.CutConstants;
import com.jxmcloud.business.cut.constants.CutErrorMsg;
import com.jxmcloud.business.cut.dto.client.LoginFromXLDto;
import com.jxmcloud.business.cut.dto.client.LoginNameDto;
import com.jxmcloud.business.cut.dtoCommon.EServerNoticeTypeDto;
import com.jxmcloud.business.cut.handler.UserEncryptionHandler;
import com.jxmcloud.business.cut.mapper.database.IUserLoginInfoDBMapper;
import com.jxmcloud.business.cut.model.database.DBUserLoginInfo;
import com.jxmcloud.business.cut.service.logic.IPackMessageToClient;
import com.jxmcloud.business.cut.service.nah.login.ICutLoginService;
import com.jxmcloud.business.cut.service.user.IUserActivityService;
import com.jxmcloud.business.cut.service.user.IUserBaseService;
import com.jxmcloud.business.cut.service.user.IUserManagerService;
import com.jxmcloud.business.cut.service.user.IUserOrderService;
import com.jxmcloud.business.cut.util.MyTool;
import com.jxmcloud.business.cut.util.XuanleRpcUtil;
import com.jxmcloud.business.cut.vo.InviteCodeVo;
import com.jxmcloud.business.cut.vo.client.LoginFromXLVo;
import com.jxmcloud.business.cut.vo.user.PlayerInfoVo;
import com.xlcloud.platform.api.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;


@Service
@Slf4j
public class CutLoginServiceImpl implements ICutLoginService {
    @Autowired
    private XuanleRpcUtil xuanleRpcUtil;
    @Resource
    private ICeSysParameterService ceSysParameterService;
    @Resource
    private IUserLoginInfoDBMapper userLoginInfoDBMapper;
    // ---------------------------新接口------------------------
    @Resource
    private IUserManagerService userManagerService;
    @Resource
    private IUserBaseService userBaseService;
    @Resource
    private IUserActivityService userActivityService;
    @Resource
    private IPackMessageToClient packMessageToClient;
    @Resource
    private IUserOrderService userOrderService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public LoginFromXLVo loginFromXL(LoginFromXLDto dto, PlayerInfoVo newTemp) {
        String error = CutErrorMsg.ERROR_TRUE;
        LoginFromXLVo loginFromXLVo = new LoginFromXLVo();
        do {
            TimeInterval interval = new TimeInterval();
            // 检测账号是否异常
            LoginNameDto loginNameDto = userManagerService.checkByAccount(dto.getAccount());
            // 是否是新用户
//            Integer uid = userManagerService.getUidByAccount(dto.getAccount());
            Integer uid = loginNameDto.getUid();
            // 玩家数据加载
            PlayerInfoVo player;
            if (uid.equals(0)) {
                player = userManagerService.makeNewPlayer(dto.getAccount());
            } else {
                player = userManagerService.loadPlayerFromDb(uid);
            }
            if (ObjectUtil.isNull(player)) {
                error = "玩家账号信息不存在!";
                break;
            }
            // 验证活动是否有效
            userActivityService.checkNewActivityValid(player);
            if (player.getActivity().getActivityId().equals(0)) {
                // error = "您已经参加完所有活动!";
                // 情况用户数据：重新开始活动
                userLoginInfoDBMapper.delete(new QueryWrapper<DBUserLoginInfo>().eq("account", player.getBase().getAccount()));
                player = userManagerService.makeNewPlayer(dto.getAccount());
                // break;
            }

            // 是否验证登录信息
            CeSysParameter isNeedCheck = ceSysParameterService.getParamByKeyCache(CutConstants.IS_DEED_CHECK_LOGIN);
            if (MyTool.isTure(isNeedCheck.getParameterValue())) {
                // 玄乐相关数据
//                LoginNameDto loginNameDto = xuanleRpcUtil.getUserInfoByLoginName(dto.getAccount());
                // 跟新用户信息
                userBaseService.updateFromXlData(player, loginNameDto);
            }
            // 新用户助力
            if (ObjectUtil.isNotNull(dto.getCommand())) {
                try {
                    InviteCodeVo inviteCode = UserEncryptionHandler.getInviteCode(dto.getCommand());
                    if (ObjectUtil.isNull(inviteCode)) {
                        log.error("邀请码错误! ====> {}", inviteCode);
                    } else {
                        log.info("用户助力，被助力用户：{}，助力活动：{}", inviteCode.getUid(), inviteCode.getActId());
                        userActivityService.checkAddInvitedPlayer(player, inviteCode.getUid().intValue(), inviteCode.getActId().intValue(), null);
                    }
                } catch (UnsupportedEncodingException e) {
                    log.error("ERROR: 邀请码解析失败! {}", e.getMessage());
                }
            }
            // 查找用户最近订单
            userOrderService.selectVipOrder(player);
            // 查找用户最近订单次数
            userOrderService.selectVipOrderNum(player);
            // 创建用户Session
            userBaseService.makeSession(player);
            // 移除通知消息
            userActivityService.removeNoticeType(player, EServerNoticeTypeDto.KICK_OFF);
            // ...


            // 回报数据封装
            loginFromXLVo = packMessageToClient.packPlayerLoginData(player);
            // 刷新缓存信息
            userManagerService.refreshPlayerCache(player);
            log.info("登录接口响应时长：{}ms", interval.interval());
        } while (false);
        if (!error.equals(CutErrorMsg.ERROR_TRUE)) {
            // 抛出异常
            throw new BusinessException(error);
        }
        return loginFromXLVo;
    }
}
